package scripts;

import java.io.File;
import java.util.logging.Level;

import model.Preference;
import model.Settings;
import util.LoggingUtils;
import util.PlayerUtilities;

public class JarFileScriptRunner {
	String path;
	private String scriptFileName;
	
	public JarFileScriptRunner(String relativePathInJar) {
		this.path = relativePathInJar;
		File file= new File(path);
		String fileName = file.getName();
		this.scriptFileName = fileName;
	}
	
	public void executeScript() {
		copyScriptToLocal();
		givePermission();
		runScript();
	}

	private void runScript() {
		ProcessBuilder pb = new ProcessBuilder("./"+scriptFileName);
		pb.directory(new File(Settings.SCRIPT_DIRECTORY));
		pb.environment().put("ROOT_PSWD", Preference.getInstance().getRootPassword());
		try {
			pb.start();
		} catch (Exception e) {
			LoggingUtils.log(Level.SEVERE, "Error in JarFileScriptRunner .runScript() "+e.getMessage(), e);
			e.printStackTrace();
		}
		
	}
	
	private void copyScriptToLocal() {
		PlayerUtilities.copyFromJarToDirectory(path, Settings.SCRIPT_DIRECTORY+scriptFileName);
	}
	
	private void givePermission() {
		PermissionSetter chmodSetter = new PermissionSetter();
		chmodSetter.givePermission(Settings.SCRIPT_DIRECTORY+scriptFileName, "a+x");
	}
}
